from django.shortcuts import render
from alipay import AliPay
from django import http
from django.conf import settings
import os

from meiduo_mall.utils.views import LoginRequiredView
from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RETCODE
from .models import Payment


class PaymentURLView(LoginRequiredView):
    """拼接支付宝url"""
    def get(self, request, order_id):
        # 校验
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单有误')

        # 创建Alipay 工具对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # /Users/chao/Desktop/meiduo_33/meiduo_mall/meiduo_mall/apps/payment/views.py
            # /Users/chao/Desktop/meiduo_33/meiduo_mall/meiduo_mall/apps/payment/keys/app_private_key.pem
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),  # 应用私钥文件的绝对路径
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 是不是沙盒应用
        )
        # 调用Alipay api_alipay_trade_page_pay 方法得到支付宝查询参数
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 美多订单编号
            total_amount=str(order.total_amount),  # 实付金额 注意转换类型
            subject='美多商城:%s' % order_id,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功后的回调url
        )
        # 拼接完整的url
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string  # 真实环境
        # 电脑网站支付，需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string  # 沙箱环境
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentSuccessView(LoginRequiredView):
    """支付成功回调处理"""
    def get(self, request):
        # 1.接收查询参数
        query_dict = request.GET
        # 2.将查询参数QueryDict转换dict
        data = query_dict.dict()
        # 3. 将查询参数中的sign移除
        sing = data.pop('sign')
        # 4. 创建alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # /Users/chao/Desktop/meiduo_33/meiduo_mall/meiduo_mall/apps/payment/views.py
            # /Users/chao/Desktop/meiduo_33/meiduo_mall/meiduo_mall/apps/payment/keys/app_private_key.pem
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 应用私钥文件的绝对路径
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 是不是沙盒应用
        )
        # 5. 调用alipay  verify方法进行验证
        result = alipay.verify(data, sing)
        if result:
            # 获取美多订单编号
            order_id = data.get('out_trade_no')
            # 支付交易流水号
            trade_no = data.get('trade_no')
            try:
                # 来存储之前先查询
                Payment.objects.get(trade_id=trade_no)
            except Payment.DoesNotExist:
                # 保存支付结果
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_no
                )
                # 修改订单状态
                OrderInfo.objects.filter(order_id=order_id,
                                         user=request.user,
                                         status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            # 响应
            return render(request, 'pay_success.html', {'trade_id': trade_no})
        else:
            return http.HttpResponseBadRequest('支付异常')